import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'

// 路由懒加载
const LoginVue = () => import('@/views/Login.vue')
const LayoutVue = () => import('@/views/Layout.vue')
const ArticleCategoryVue = () => import('@/views/article/ArticleCategory.vue')
const ArticleManageVue = () => import('@/views/article/ArticleManage.vue')
const UserAvatarVue = () => import('@/views/user/UserAvatar.vue')
const UserInfoVue = () => import('@/views/user/UserInfo.vue')
const UserResetPasswordVue = () => import('@/views/user/UserResetPassword.vue')
const NotFoundVue = () => import('@/views/NotFound.vue')

const routes = [
    { 
        path: '/login', 
        component: LoginVue,
        meta: { title: '登录' }
    },
    {
        path: '/',
        component: LayoutVue,
        redirect: '/article/manage',
        meta: { requiresAuth: true },
        children: [
            { path: '/article/category', component: ArticleCategoryVue, meta: { title: '文章分类' } },
            { path: '/article/manage', component: ArticleManageVue, meta: { title: '文章管理' } },
            { path: '/user/info', component: UserInfoVue, meta: { title: '个人信息' } },
            { path: '/user/avatar', component: UserAvatarVue, meta: { title: '更换头像' } },
            { path: '/user/resetPassword', component: UserResetPasswordVue, meta: { title: '重置密码' } }
        ]
    },
    { 
        path: '/:pathMatch(.*)*', 
        component: NotFoundVue,
        meta: { title: '404' }
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const tokenStore = useTokenStore()
    
    if (to.meta.requiresAuth && !tokenStore.token) {
        ElMessage.warning('请先登录')
        next('/login')
    } else {
        // 设置页面标题
        document.title = to.meta.title ? `${to.meta.title} - 管理系统` : '管理系统'
        next()
    }
})

export default router
